import router from './router';
import store from './store';

const whiteList = ['/login'];

router.beforeEach((to, from, next) => {
  const token = window.localStorage.getItem('token');
  if (token) {
    if (to.path === '/login') {
      next('/home');
    } else {
      if (store.state.routes.length === 0) {
        store.dispatch('getRoutes').then((routes) => {
          routes.forEach((route) => {
            router.addRoute(route);
          });
          next();
        });
      } else {
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login`);
    }
  }
});
